<template>

    <div class="m">
        <h1>用户信息</h1>
        <div class="m_des">

            <table border="0" style="width:870px; line-height:22px;" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr valign="top">
                        <td>
                            <div>用户名：<span style="color:#555555;">{{ user.userName }}</span></div>
                            <div style="margin-top:8px;">欢迎来到易买网！</div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- <div v-if="userType==0">
        <div class="mem_t">资产信息</div>
        <table border="0" class="mon_tab" style="width:870px; margin-bottom:20px;" cellspacing="0" cellpadding="0">
            <tbody>
                <tr>
                    <td colspan="3">订单提醒：
                        <span style="font-family:'宋体';">待付款(<span>0</span>) &nbsp; &nbsp; &nbsp; &nbsp;
                            待收货(<span>2</span>)
                        </span>

                    </td>
                </tr>
            </tbody>
        </table>
        </div>   -->

        <div class="mem_t">账号信息</div>
        <table border="0" class="mon_tab" style="width:870px; margin-bottom:20px;" cellspacing="0" cellpadding="0">
            <tbody>
                <!-- 查看模式 -->
                <template v-if="!isEditing">
                    <tr>
                        <td>电&nbsp; &nbsp; 话：<span style="color:#555555;">{{ user.mobile }}</span></td>
                        <td>邮&nbsp; &nbsp; 箱：<span style="color:#555555;">{{ user.email }}</span></td>
                    </tr>
                    <tr>
                        <td>身份证号：<span style="color:#555555;">{{ user.identityCode }}</span></td>
                        <td>注册时间：<span style="color:#555555;">{{ new Date(user.createDate).toLocaleDateString()
                                }}</span>
                        </td>
                    </tr>
                    <tr>
                        <td>性&nbsp; &nbsp; 别：<span style="color:#555555;">{{ user.sex == '1' ? '男' : '女' }}</span></td>

                        <td>
                            <button @click="startEdit" class="edit-btn">修改信息</button>
                        </td>
                    </tr>
                </template>

                <!-- 编辑模式 -->
                <template v-else>
                    <tr>
                        <td>账号(不可改)：
                            <input v-model="editForm.loginName" type="text" class="edit-input" readonly />
                        </td>
                        <td>邮箱(不可改)：
                            <input v-model="editForm.email" @blur="validateEmail" type="email" class="edit-input"  readonly/>
                            <div v-if="errors.email" class="error-text">{{ errors.email }}</div>
                        </td>
                        
                    </tr>
                    <tr>
                        <td>用户名：
                            <input v-model="editForm.userName"  @blur="validateUsername" type="text" class="edit-input" />
                            <span v-if="errors.userName" class="error-text">{{ errors.userName }}</span>
                        </td>
                        <td>原密码：
                            <input v-model="editForm.oldPassword" @blur="validateOldPassword" type="password"
                                class="edit-input" />
                            <div v-if="errors.oldPassword" class="error-text">{{ errors.oldPassword }}</div>
                        </td>

                       
                    </tr>

                    <tr>
                         <td>新密码：
                            <input v-model="editForm.newPassword" @blur="validatePassword" type="password"
                                class="edit-input" />
                            <div v-if="errors.newPassword" class="error-text">{{ errors.newPassword }}</div>
                        </td>
                        <td>确认密码
                            <input v-model="editForm.scpassword" @blur="validateConfirmPassword" type="password"
                                class="edit-input" />
                            <div v-if="errors.scpassword" class="error-text">{{ errors.scpassword }}</div>
                        </td>
                       

                    </tr>
                    <tr>
                         <td>电&nbsp; &nbsp; 话：
                            <input v-model="editForm.mobile" @blur="validatePhone" type="text" class="edit-input" />
                            <div v-if="errors.mobile" class="error-text">{{ errors.mobile }}</div>
                        </td>
                        <td>身份证号：
                            <input v-model="editForm.identityCode" @blur="validateIDCard" type="text"
                                class="edit-input" />
                            <div v-if="errors.identityCode" class="error-text">{{ errors.identityCode }}</div>
                        </td>

                    </tr>
                    <tr>
                        <td>性&nbsp; &nbsp; 别：
                            <label>
                                <input type="radio" name="sex" v-model="editForm.sex" value='1' /> 男

                            </label>
                            <label>
                                <input type="radio" name="sex" v-model="editForm.sex" value='0' /> 女

                            </label>
                            <div v-if="errors.sex" class="error-text">{{ errors.sex }}</div>
                        </td>
                    </tr>
                    <tr>

                        <td>
                            <button @click="saveEdit" class="save-btn">保存</button>
                            <button @click="cancelEdit" class="cancel-btn">取消</button>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'

const userType = sessionStorage.getItem('type')
const user = ref({
    userName: '',
    loginName: '',
    mobile: '',
    email: '',
    identityCode: '',
    createDate: '',
    sex: '',
    id: '',
    password: ''
})

const isEditing = ref(false)
const editForm = ref({
    id: '',
    userName: '',
    loginName: '',
    oldPassword: '',
    newPassword: '',
    scpassword: '',
    mobile: '',
    email: '',
    identityCode: '',
    sex: ''
})

// 添加错误信息对象
const errors = reactive({})

// 开始编辑
const startEdit = () => {
    editForm.value = { ...user.value }
    isEditing.value = true
}


// 验证用户名
const validateUsername = () => {
    if (!editForm.value.userName || !editForm.value.userName.trim()) {
        errors.userName = '请输入用户名'
        return false
    } else if (editForm.value.userName.length < 3) {
        errors.userName = '用户名至少3个字符'
        return false
    } else {
        delete errors.userName
        return true
    }
}


// 验证原密码
const validateOldPassword = async () => {
    const userID = sessionStorage.getItem('id')

    console.log('用户ID:', userID);
    console.log('用户ID:', editForm.value.oldPassword);

    if (!editForm.value.oldPassword || !editForm.value.oldPassword.trim()) {
        errors.oldPassword = '请输入原密码'
        return false
    }

    const response = await axios.post('/api/isOldPassword', null, {
        params: {
            id: userID,
            oldPassword: editForm.value.oldPassword
        }
    })

    if (response.data.code !== 5200) {
        errors.oldPassword = '原密码错误'
        return false
    } else {
        delete errors.oldPassword
        return true
    }
}
// 验证密码
const validatePassword = () => {
    if (editForm.value.newPassword && editForm.value.newPassword.length < 6) {
        errors.newPassword = '密码至少6个字符'
        return false
    } else {
        delete errors.newPassword
        return true
    }
}

// 验证确认密码
const validateConfirmPassword = () => {
    if (editForm.value.newPassword !== editForm.value.scpassword) {
        errors.scpassword = '两次输入的密码不一致'
        return false
    } else {
        delete errors.scpassword
        return true
    }
}

// // 验证邮箱
// const validateEmail = () => {
//     const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
//     if (!editForm.value.email) {
//         errors.email = '请输入邮箱'
//         return false
//     }
//     if (!emailRegex.test(editForm.value.email)) {
//         errors.email = '邮箱格式应为（xxx@xxx.xxx）'
//         return false
//     } else {
//         delete errors.email
//         return true
//     }
// }

// 验证手机号
const validatePhone = () => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!editForm.value.mobile) {
        errors.mobile = '请输入手机号'
        return false
    } else if (!phoneRegex.test(editForm.value.mobile)) {
        errors.mobile = '手机号格式不正确(13-19开头的11位数字)'
        return false
    } else {
        delete errors.mobile
        return true
    }
}

// 验证身份证号
const validateIDCard = () => {
    // 身份证号正则表达式（18位）
    const idCardRegex = /^[1-9][0-9]\d{8}$/

    if (!editForm.value.identityCode.trim()) {
        errors.identityCode = '请输入身份证号'
        return false
    } else if (!idCardRegex.test(editForm.value.identityCode)) {
        errors.identityCode = '身份证号格式不正确（10位）'
        return false
    } else {
        delete errors.identityCode
        return true
    }
}

// 验证表单
const validateForm = async () => {
    const isUsernameValid = validateUsername()
    const isPasswordValid = validatePassword()
    const isConfirmPasswordValid = validateConfirmPassword()
    // const isEmailValid = validateEmail()
    const isPhoneValid = validatePhone()
    const isIDCardValid = validateIDCard()
    const isValidateOldPassword = await validateOldPassword()

    return isUsernameValid && isPasswordValid && isConfirmPasswordValid  && isPhoneValid && isIDCardValid && isValidateOldPassword
}

// 保存编辑
const saveEdit = async () => {
    const isValid = await validateForm()
    if (!isValid) {
        alert('请完善表单信息')
        return
    }

    if (editForm.value.newPassword && editForm.value.newPassword !== editForm.value.scpassword) {
        alert('两次输入的密码不一致')
        return
    }


    const updateData = {
        id: user.value.id,
        userName: editForm.value.userName,
        mobile: editForm.value.mobile,
        email: editForm.value.email,
        identityCode: editForm.value.identityCode,
        sex: editForm.value.sex,
        password: '',
    }

    // 只有当新密码不为空时才更新密码
    if (editForm.value.newPassword != '' && editForm.value.newPassword != null) {
        updateData.password = editForm.value.newPassword
    }

    const response = await axios.post('/api/updateUser', updateData, {
        headers: {
            'Content-Type': 'application/json'
        }
    })

    if (response.data.code === 5200) {
        alert('更新成功')



        const id = sessionStorage.getItem('id');
        await axios.post('/api/loginOutUser', {
            id: id
        })
        alert('账号信息已修改,请重新登录')

        window.sessionStorage.removeItem('id')
        window.sessionStorage.removeItem('token')
        window.sessionStorage.removeItem('loginName')
        window.sessionStorage.removeItem('userName')
        window.sessionStorage.removeItem('type')
        window.location.href = '/login'
        return;


    } else {
        alert('更新失败')
    }

}

// 取消编辑
const cancelEdit = () => {
    isEditing.value = false
    // 清除所有错误信息
    Object.keys(errors).forEach(key => {
        delete errors[key]
    })
}

//获取用户信息
const getUser = async () => {
    const id = sessionStorage.getItem('id')
    console.log('id:', id);

    if (id) {
        const response = await axios.get('/api/getUser', {
            params: { id: id }
        })


        if (response.data.code === 5200) {
            user.value = response.data.user
        } else {
            alert('获取用户信息失败')
        }
    } else {
        alert('用户信息获取失败')
    }
};

onMounted(async () => {
    getUser();
});

onMounted(async () => {
    getUser();
})

</script>

<style scoped>
.m {
    background-color: white;
    height: 800px;
}

.edit-input {
    border: 1px solid #ccc;
    padding: 3px 5px;
    border-radius: 3px;
    width: 150px;
}

.edit-input.error {
    border: 1px solid #ff4e00;
}

.error-text {
    color: #ff4e00;
    font-size: 12px;
    margin-top: 3px;
}

.edit-btn,
.save-btn,
.cancel-btn {
    padding: 5px 15px;
    margin-right: 10px;
    border: none;
    border-radius: 3px;
    cursor: pointer;
}

.edit-btn {
    background-color: #007bff;
    color: white;
}

.save-btn {
    background-color: #28a745;
    color: white;
}

.cancel-btn {
    background-color: #6c757d;
    color: white;
}

.edit-btn:hover {
    background-color: #0056b3;
}

.save-btn:hover {
    background-color: #218838;
}

.cancel-btn:hover {
    background-color: #5a6268;
}

label {
    margin-right: 15px;
    cursor: pointer;
}
</style>